define(function(require, exports){
	var $ = require('jquery');
	var util = require('util');
	var pubjs	= require('pubjs');
	var popwin	= require('@base/dialog').base;
	var view = require('@base/view');
	var createSweetyBase = require('sweety/action/edit').base;
	var createWhiskyBase = require('whisky/action/edit').base;

	// 活动编辑 —— 选择创意包内容视图
	var SelectView = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'addText': LANG('新建')
				,'gridConfig': {
					reqType: 'websocket'
					,opClick: true
					,hasTab: false
					,hasMenu: false
					,hasPager: true
					,hasSearch: true
					,hasExport: false
					,hasAmount: false
					,auto_load: false
					,param: {
						noAmount: true,
						metrics: ['click_rate', 'back_reg_rate'],
						limit: 10
					}
					,sort: 'click_rate'
					,pager: {
						size: 10
						,stepButton: true
						,showSizeTypes: 0
						,showJumper: 0
					}
					,'list': {
						'rowSelect': true,
						'rowSelectOp': true
					}
				}
				,'hasCreateBtn': true
				,'class': 'M-HighGrid'
				,'silence': false
			});

			this.$selectData = [];
			this.$selected = {};
			this.Super('init', arguments);
		}
		,afterBuild: function() {
			var el = this.getDOM();
			var doms = this.$doms = {};
			var c = this.getConfig();

			doms.tagContainer = $('<div class="tag-container"></div>').appendTo(el);
			doms.gridContainer = $('<div class="grid-container pr"></div>').appendTo(el);
			if(c.addText)
			{
				doms.createBtn = $('<button class="btn btn-primary pa top-right z2">' + c.addText + '</button>').appendTo(doms.gridContainer).toggle(c.hasCreateBtn);
				this.uiBind(doms.createBtn, 'click', 'eventCreateBtnClick');
			}

			this.createAsync('grid', '@base/grid.base', util.extend({
				target: doms.gridContainer
			}, this.getConfig('gridConfig'), function (mod) {
				mod.reset();
			}));

			this.buildFromTemplate();
		}
		,renderName: function(i, val){
			// TODO: 缩略图
			return '<div class="uk-text-truncate tl w200" title="' + val + '">' + val + '</div>';
		}
		,renderStatus: function(i, val, data) {
			var status, title;
			if (data["IsDeleted"]) {
				status = 'store';
				title = LANG('归档')
			} else {
				status = (+data["Status"]===1) ? 'running': 'pause';
				title = (+data["Status"]===1) ? LANG('启用'): LANG('暂停');
			}

			return '<i title="'+title+'" class="'+status+' mr5"></i>';
		}
		,renderOperate: function(i, val, row) {
			if (this.$selected[row._id]) {
				return '<button data-op="unselect" class="btn btn-success">' + LANG('取消') + '</button>';
			} else {
				return '<button data-op="select" class="btn btn-default">' + LANG('添加') + '</button>';
			}
		}
		,reset: function() {
			this.$selectData = [];
			this.$selected = {};
			// this.$.tag.reset();
			if(this.$ && this.$.grid)
			{
				this.$.grid.reset();
			}

			return this;
		}
		,setParam: function(param) {
			if(this.$.grid) {
				this.$.grid.setParam(param);
			}

			return this;
		}
		,load: function() {
			// this.$.tag.load();
			this.loadGrid();
			return this;
		}
		,loadGrid: function() {
			this.$.grid.setParam({ExchangeId: this.$exchangeId}).load();
			return this;
		}
		,updateSelect: function() {
			var self = this;
			self.$selected = {};
			util.each(this.$selectData, function (item) {
				self.$selected[item._id] = 1;
			});

			this.$.grid.updateOperation();
		}
		,addSelected: function(item) {
			this.addSelectData(item);
			this.updateSelect();
		}
		,removeSelected: function(item) {
			this.unSelectData(item);
			this.updateSelect();
		}
		,setSelectData: function (data) {
			this.$selectData = data;
			this.updateSelect();
			return this;
		}
		,getSelectData: function () {
			return this.$selectData;
		}
		,addSelectData: function (data) {
			for(var i = 0; i < this.$selectData.length; i++)
			{
				if(this.$selectData[i]._id === data._id)
				{
					return;
				}
			}

			this.$selectData.push(data);
		}
		,unSelectData: function (data) {
			for(var i = 0; i < this.$selectData.length; i++)
			{
				if(this.$selectData[i]._id === data._id)
				{
					return this.$selectData.splice(i, 1);
				}
			}
		}
		// 添加按钮
		,eventCreateBtnClick: function(ev) {
			this.fire('create');
		}
		// 渠道更改消息, 渠道变更时广播
		,onExchangeIdChange: function(ev) {
			this.$exchangeId = ev.param;
		}
		,onListOpClick: function(ev) {
			switch(ev.param.op){
				case "select":
					this.addSelected(ev.param.data);
				break;

				case "unselect":
					this.removeSelected(ev.param.data);
				break;
			}
			return false;
		}
		// 标签选中消息
		,onSimpleLabelChange: function(ev) {
			this.$.grid.setParam({
				tags: ev.param
			}).load();
		}
	});
	exports.selectView = SelectView;

	exports.selectSweety = SelectView.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'addText': LANG('新建创意包'),
				'gridConfig': {
					url: 'sweety/selectList'
					,cols: [
						{name:'_id', text:"ID", width: 50, sort: true}
						,{name:'Status', text: LANG('状态'), width: 30, render: 'renderStatus'}
						,{name:'Name', text: LANG("创意包"), width: 210, render: 'renderName'}
						// ,'SweetyNameWithThumb'
						,{name:'click_rate', sort:true}
						,{name:'back_reg_rate', sort:true}
						,{name:'op',text: LANG("操作"), type: 'op', render: 'renderOperate',width:120}
					]
					,param: {
						AdvertiserId: +util.getQueryString('aderId'),
						PlanId: +util.getQueryString('planId'),
						CampaignId: +util.getQueryString('campaignId')
					}
				}
			});

			this.Super('init', arguments);
		}
	});

	exports.selectWhisky = SelectView.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'addText': LANG('新建落地页'),
				'gridConfig': {
					url: 'whisky/selectList'
					,cols: [
						{name:'_id', text:"ID", width: 50, sort: true}
						,{name:'Status', text: LANG('状态'), width: 30, render: 'renderStatus'}
						,{name:'Name', text: LANG("落地页"), width: 210, render: 'renderName'}
						,{name:'click_rate', sort:true}
						,{name:'back_reg_rate', sort:true}
						,{name:'op',text: LANG("操作"), type: 'op', render: 'renderOperate',width:120}
					]
					,param: {
						AdvertiserId: +util.getQueryString('aderId'),
						PlanId: +util.getQueryString('planId'),
						CampaignId: +util.getQueryString('campaignId')
					}
				}
			});

			this.Super('init', arguments);
		}
	});

	exports.selectMaterialGroup = SelectView.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'addText': LANG(''),
				'gridConfig': {
					url: 'materialGroup/list',
					hasBatch: false,
					hasDetail: false,
					hasMenu: false,
					hasSelect: false,
					cols: [
						{name:'_id',text:"ID", sort: true, width: 60, align: 'center'},
						{name:'Name', text: LANG("名称"), width: 150, align: 'center'},
						{name:'StrategyInfo', text: LANG("创意包落地页"), width: 200, render: 'renderStrategy', align: 'center'},
						{name:'UpdateTime', text: LANG("更新时间"), width: 150, render: 'renderTime', align: 'center'},
						{name:'op',text: LANG("操作"), type: 'op', render: 'renderOperate',width:120}
					]
				}
			});

			this.Super('init', arguments);
		}
	});

	exports.createSweety = createSweetyBase.extend({
		init: function(config) {
			config = pubjs.conf(config, {
			});
			this.Super('init', arguments);
		}
		,afterBuildTemplate: function() {
			this.$.save.hide();
			this.$.cancel.hide();
			this.$.saveNotify.hide();
		}
		,afterSave: function(err, data) {
			var res = this.Super('afterSave', arguments);
			this.$.saveNotify.hide();
			if (res !== false) {
				this.fire('afterCreate', res);
			}
		}
/*		,getValue: function() {
			var data = this.Super('getValue', arguments);
			data.Products = this.$product;
			return data;
		}*/
		,setProduct: function(value) {
			this.$product = value;
			return this;
		}
		,reset: function() {
			this.Super('reset', arguments);
			this.vm.$.view.product = false;
			return this;
		}
	});

	// 活动编辑 —— 新建落地页内容视图
	exports.createWhisky = createWhiskyBase.extend({
		init: function(config) {
			config = pubjs.conf(config, {
			});
			this.Super('init', arguments);
		}
		,afterBuildTemplate: function() {
			this.$.save.hide();
			this.$.cancel.hide();
			this.$.saveNotify.hide();
		}
		,onSave: function() {
			var res = this.Super('onSave', arguments);
			this.$.saveNotify.hide();
			if (res !== false) {
				this.fire('afterCreate',res);
			}
		}
/*		,getData: function() {
			var data = this.Super('getData', arguments);
			data.Products = this.$product;
			return data;
		}*/
		,setProduct: function(value) {
			this.$product = value;
			return this;
		}
		,reset: function() {
			this.Super('reset', arguments);
			this.vm.$.view.product = false;
			return this;
		}
	});
	// 活动编辑 —— 选择创意包入口模块
	var Main = popwin.extend({
		init:function(config) {
			config = pubjs.conf(config, {
				'title': LANG('选择创意包'),
				'hasCreate': true,
				'width': 900,
				'height': 650,
				'showFoot': true,
				'class': 'P-campaign-selectSweety',
				'silence': true,
				'size': 'l',
				'selectUri': '',
				'createUri': '',
				'addText': '',
				'selectText': '',
				'fireEvent': ''
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.Super('afterBuild', arguments);
			var c = this.getConfig();
			var el = this.getContainer();

			this.$selectContainer = $('<div class="select-container"></div>').appendTo(el);
			this.createAsync('select', c.selectUri, {
				target: this.$selectContainer
			});

			if(c.hasCreate)
			{
				this.$createContainer = $('<div class="create-container"></div>').appendTo(el);
				this.createAsync('create', c.createUri, {
					target: this.$createContainer
				});
			}
		}
		,reset: function() {
			this.$.select.reset();
			this.switchToSelect();
			return this;
		}
		,load: function() {
			if (this.$isCreate) {
				this.$.create.load();
			} else {
				this.$.select.load();
			}
			return this;
		}
		,setParam: function(param) {
			if(this.$.select) {
				if(param.Products)
				{
					this.$.create.setProduct(param.Products);
				}

				this.$.select.setParam(param);
			}

			return this;
		}
		,setValue: function(selected) {
			this.$.select.setSelectData(selected);
			return this;
		}
		,getValue: function() {
			return this.$.select.getSelected();
		}
		// 根据$isCreate属性在新建和选择界面之间切换
		,updateView: function() {
			var self = this;
			var c = self.getConfig();
			if (self.$isCreate) {
				self.$.create.reset();
				self.setTitle(c.addText);
			} else {
				self.setTitle(c.selectText);
			}

			if(c.hasCreate)
			{
				self.$createContainer.toggle(self.$isCreate);
			}
			self.$selectContainer.toggle(!self.$isCreate);
		}
		// 切换到选择视图
		,switchToSelect: function() {
			this.$isCreate = false;
			this.updateView();
			return this;
		}
		// 切换到创建视图
		,switchToCreate: function() {
			this.$isCreate = true;
			this.updateView();
			return this;
		}
		// 添加消息
		,onCreate: function() {
			this.switchToCreate();
			return false;
		}
		// 添加保存消息
		,onAfterCreate: function(data) {
			this.switchToSelect();
			this.$.select.addSelected(data.param);
			this.$.select.loadGrid();
		}
		,onOk: function(ev) {
			if(ev.from._.pid === this._.guid)
			{
				if (this.$isCreate) {
					this.$.create.save();
				} else {
					var c = this.getConfig();
					if(!c.silence)
					{
						this.fire(c.fireEvent, this.$.select.getSelectData())
					}

					this.hide();
				}

				return false;
			}
		}
		,onCancel: function(ev) {
			// 暂时取消这个限制，因为点击新建创意包右上角的关闭按钮，不能切回选择创意包列表
			// 暂时没发现取消限制后的影响，如果有问题，后面再做修改整理
			// if((ev && ev.from && ev.from._.pid) === this._.guid)
			// {
				if (this.$isCreate) {
					this.switchToSelect();
				} else {
					this.hide();
				}
				return false;
			// }
		}
	});

	exports.sweety = Main.extend({
		init:function(config) {
			config = pubjs.conf(config, {
				'title': LANG('选择创意包'),
				'width': 900,
				'height': 650,
				'showFoot': true,
				'class': 'P-campaign-selectSweety',
				'silence': true,
				'size': 'l',
				'selectUri': 'modules/selectModule.selectSweety',
				'createUri': 'modules/selectModule.createSweety',
				'addText': LANG('新建创意包'),
				'selectText': LANG('选择创意包'),
				'fireEvent': 'selectSweety'
			});

			this.Super('init', arguments);
		}
	});

	exports.whisky = Main.extend({
		init:function(config) {
			config = pubjs.conf(config, {
				'title': LANG('选择落地页'),
				'width': 900,
				'height': 750,
				'showFoot': true,
				'class': 'P-campaign-selectWhisky',
				'silence': true,
				'size': 'l',
				'selectUri': 'modules/selectModule.selectWhisky',
				'createUri': 'modules/selectModule.createWhisky',
				'addText': LANG('新建落地页'),
				'selectText': LANG('选择落地页'),
				'fireEvent': 'selectWhisky'
			});

			this.Super('init', arguments);
		}
	});

	exports.materialGroup = Main.extend({
		init:function(config) {
			config = pubjs.conf(config, {
				'title': LANG('素材组列表'),
				'width': 900,
				'height': 750,
				'hasCreate': false,
				'showFoot': true,
				'silence': true,
				'size': 'l',
				'selectUri': 'modules/selectModule.selectMaterialGroup',
				'createUri': '',
				'fireEvent': 'selectMaterialGroup'
			});

			this.Super('init', arguments);
		}
	});
});
